package com.scitc.pleasurevideo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.google.android.material.appbar.AppBarLayout;
import com.jaeger.library.StatusBarUtil;
import com.scitc.pleasurevideo.adapter.MenuTvContentAdapter;
import com.scitc.pleasurevideo.base.ETActivity;
import com.scitc.pleasurevideo.data.ETMan;
import com.scitc.pleasurevideo.datasql.VideoSourceSqlData;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.imgutil.ImageManager;
import com.scitc.pleasurevideo.pojo.DoubanTvVo;
import com.scitc.pleasurevideo.pojo.MenuTvVo;
import com.scitc.pleasurevideo.pojo.VideoSourceVo;
import com.scitc.pleasurevideo.util.AtyContainer;
import com.scitc.pleasurevideo.util.ConstUtil;
import com.scitc.pleasurevideo.util.MenuUrlUtil;
import com.scitc.pleasurevideo.util.UIHelper;
import com.scitc.pleasurevideo.view.CoordListView;
import com.scitc.pleasurevideo.woview.SettingVideoSourceListActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class TvMenuContentActivity extends ETActivity {

    private AppBarLayout appbarLayout;
    private ImageView igTvImgBig;
    private RelativeLayout rlTvInformation;
    private TextView tvIntroduction;
    private TextView tvOpenCollect;
    private LinearLayout llTvImgSmallBox;
    private ImageView igTvImgSmall;
    private TextView tvTvName;
    private TextView tvDirectors;
    private TextView tvCasts;
    private CoordListView mListView;
    private RelativeLayout titleContainer;
    private RelativeLayout rlVideoSourceSetting;
    private RelativeLayout back;
    private TextView headerTitle;
    private RelativeLayout rlShare;
    private TextView tvTVNum;
    private TextView tvSerachType;
    private TextView tvVideoSourceText;
    private ImageView igBackImg;
    private Toolbar tbToolbar;

    private MenuTvContentAdapter mAdapter;
    private List<MenuTvVo> items = new ArrayList<MenuTvVo>();
    private Context context;
    private DoubanTvVo doubanTvPojo;
    private String mListViewClickType = "null";
    private int itemNum = 0;
    private int clCoordinatorTopPanding = 0;
    private View footerView;
    private String tvIntroductionString = "";

    public TvMenuContentActivity() {
        super();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StatusBarUtil.setTranslucent(mInstance, 0);

        this.setContentView(R.layout.activity_tv_menu_content);

        context = this;

        doubanTvPojo = (DoubanTvVo) getIntent().getSerializableExtra("doubanTvPojo");


        formatTitle();

        initView();

        loadFooterView();

        initViewData();

        loadData();

        onClick();

    }


    private void formatTitle(){
        if (doubanTvPojo.getTitle().indexOf(' ') != -1) {
            doubanTvPojo.setTitle(doubanTvPojo.getTitle().substring(0, doubanTvPojo.getTitle().indexOf(' ')));
        }
        doubanTvPojo.setTitle(StringFilter(doubanTvPojo.getTitle()));
    }

    public static String StringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
//
//        Pattern p = Pattern.compile(regEx);
//        Matcher m = p.matcher(str);
//        return m.replaceAll("").trim();

        int len=-1;
        for (int i = str.length()-1; i >= 0; i--) {
            if(regEx.contains(str.charAt(i)+"")){
                len=i;
            }else {
                break;
            }
        }
        if(len>=0){
            str=str.substring(0,len);
        }
        len=-1;
        for (int i = 0; i < str.length(); i++) {
            if(regEx.contains(str.charAt(i)+"")){
                len=i;
            }else {
                break;
            }
        }
        if(len>=0){
            str=str.substring(len+1,str.length());
        }

        return str;
    }


    /**
     * 加载footerView
     */
    private void loadFooterView() {
        LayoutInflater layoutInflater = LayoutInflater.from(mInstance);
        footerView = layoutInflater.inflate(R.layout.item_null_white, mListView, false);
        mListView.addFooterView(footerView);
    }

    /**
     * 初始化数据
     */
    private void initViewData() {
        headerTitle.setText(doubanTvPojo.getTitle());
        tvTvName.setText(doubanTvPojo.getTitle());
        ImageManager.bindImageCenterCrop(this, igTvImgBig, doubanTvPojo.getCover());
        ImageManager.bindImageCenterCrop(this, igTvImgSmall, doubanTvPojo.getCover());

        String temp = "导演:";
        if (doubanTvPojo.getDirectors() == null || doubanTvPojo.getDirectors().size() < 1) {
            temp += "暂无数据";
        } else {
            for (int i = 0; i < doubanTvPojo.getDirectors().size(); i++) {
                if (i == doubanTvPojo.getDirectors().size() - 1) {
                    temp += doubanTvPojo.getDirectors().get(i);
                } else {
                    temp += doubanTvPojo.getDirectors().get(i) + ",";
                }
            }
        }
        tvDirectors.setText(temp);

        temp = "演员:";
        if (doubanTvPojo.getCasts() == null || doubanTvPojo.getCasts().size() < 1) {
            temp += "暂无数据";
        } else {
            for (int i = 0; i < doubanTvPojo.getCasts().size(); i++) {
                if (i == doubanTvPojo.getCasts().size() - 1) {
                    temp += doubanTvPojo.getCasts().get(i);
                } else {
                    temp += doubanTvPojo.getCasts().get(i) + ",";
                }
            }
        }
        tvCasts.setText(temp);

        tvIntroduction.setText("简介:暂无简介");
        tvOpenCollect.setVisibility(View.GONE);

    }

    /**
     * 点击事件
     */
    private void onClick() {
        //list的item的点击事件
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                if ("null".equals(mListViewClickType)) {
                    mListViewClickType = "click";
                } else {
                    return;
                }

                MenuTvVo menuTvPojo = mAdapter.getItem(position);
                ForwardHelper.toTvPlayMenuActivity((Activity) context, doubanTvPojo, menuTvPojo);

            }
        });
        //appbarlayout 滑动状态的监听
        appbarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                if (i == 0) {  //展开状态
                    headerTitle.setVisibility(View.GONE);
                    tbToolbar.setBackgroundColor(Color.parseColor("#00FFFFFF"));
                    igBackImg.setImageResource(R.mipmap.back_white);
                } else if ((Math.abs(i) + 50) >= Math.abs(appBarLayout.getTotalScrollRange())) { //折叠状态
                    headerTitle.setVisibility(View.VISIBLE);
                    tbToolbar.setBackgroundColor(Color.parseColor("#ffFFFFFF"));
                    igBackImg.setImageResource(R.mipmap.back_black);
                } else { //中间状态
                    headerTitle.setVisibility(View.GONE);
                    tbToolbar.setBackgroundColor(Color.parseColor("#00FFFFFF"));
                    igBackImg.setImageResource(R.mipmap.back_white);
                }
            }
        });
        //查看简介
        tvOpenCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("[点击展开]".equals(tvOpenCollect.getText().toString())) {
                    tvOpenCollect.setText("[点击收缩]");
                    tvIntroduction.setMaxLines(2000);
                    tvIntroduction.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10000)});
                    tvIntroduction.setText(tvIntroductionString);
                } else {
                    Log.e("TvMenuContentActivity", tvIntroduction.getText().toString());
                    tvOpenCollect.setText("[点击展开]");
                    tvIntroduction.setMaxLines(2);
                    tvIntroduction.setFilters(new InputFilter[]{new InputFilter.LengthFilter(45)});
                    tvIntroduction.setText(tvIntroductionString);
                }
            }
        });
        //设置影视来源
        rlVideoSourceSetting.setOnClickListener(v -> {
            ForwardHelper.toSettingVideoSourceListActivity(mInstance);
        });
        //设置完影视来源后，可以重新搜索
        tvSerachType.setOnClickListener(v -> {
            tvSerachType.setVisibility(View.GONE);
            mAdapter.clearItem();
            itemNum = 0;
            tvTVNum.setText("共有" + itemNum + "个结果");
            loadData();
        });
        //设置影视来源的回调
        SettingVideoSourceListActivity.setOnVideoSourceNumberStr(selectStr -> {
            if(!selectStr.equals(tvVideoSourceText.getText().toString())){
                tvVideoSourceText.setText(selectStr);
                tvSerachType.setVisibility(View.VISIBLE);
            }
        });
        //返回按钮
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        //子线程加载视频的简介
        runOnUiThread(() -> MenuUrlUtil.getTvIntroduction(doubanTvPojo.getId(), context));

        final List<VideoSourceVo> urlApiPojoList = MenuUrlUtil.getUrlApiList();

        if(urlApiPojoList==null||urlApiPojoList.size()<1){
            Toast.makeText(mInstance, "没有视频资源列表，请到设置界面，更新影视源", Toast.LENGTH_SHORT).show();
            return;
        }

        runOnUiThread(() -> {
            for (VideoSourceVo urlApiPojo : urlApiPojoList) {
                MenuUrlUtil.getMenuUrlOkgo(context, urlApiPojo.getSource_url_html_str(), urlApiPojo.getSource_url_search_str(), doubanTvPojo.getTitle());
            }
        });


        MenuUrlUtil.setMenuTvListListenr(new MenuUrlUtil.MenuTvListListenr() {
            @Override
            public void menuTvListListenr(List<MenuTvVo> menuTvPojoList) {

                for (int i = 0; i < menuTvPojoList.size(); i++) {
                    if (menuTvPojoList.get(i).getName().indexOf(doubanTvPojo.getTitle()) < 0) {

                        menuTvPojoList.remove(i);
                        i--;
                    }
                }
                if (menuTvPojoList == null || menuTvPojoList.size() < 1) {
                    return;
                }
                mAdapter.addItems(menuTvPojoList);
                itemNum += menuTvPojoList.size();
                tvTVNum.setText("共有" + itemNum + "个结果");
            }

            @Override
            public void menuTvIntroduction(String introduction) {

                if (introduction != null || introduction.trim().length() > 1) {
                    tvIntroductionString = "简介:" + introduction;
                    tvIntroduction.setText(tvIntroductionString);
                    tvOpenCollect.setVisibility(View.VISIBLE);
                }

            }
        });


    }


    @Override
    public void onResume() {
        super.onResume();
        mListViewClickType = "null";
    }


    public void clearData() {
        mAdapter.clear();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        appbarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
        igTvImgBig = (ImageView) findViewById(R.id.igTvImgBig);
        rlTvInformation = (RelativeLayout) findViewById(R.id.rlTvInformation);
        tvIntroduction = (TextView) findViewById(R.id.tvIntroduction);
        tvOpenCollect = (TextView) findViewById(R.id.tvOpenCollect);
        llTvImgSmallBox = (LinearLayout) findViewById(R.id.llTvImgSmallBox);
        igTvImgSmall = (ImageView) findViewById(R.id.igTvImgSmall);
        tvTvName = (TextView) findViewById(R.id.tvTvName);
        tvDirectors = (TextView) findViewById(R.id.tvDirectors);
        tvCasts = (TextView) findViewById(R.id.tvCasts);
        mListView = (CoordListView) findViewById(R.id.xListView);
        titleContainer = (RelativeLayout) findViewById(R.id.titleContainer);
        back = (RelativeLayout) findViewById(R.id.back);
        headerTitle = (TextView) findViewById(R.id.headerTitle);
        rlShare = (RelativeLayout) findViewById(R.id.rl_share);
        rlVideoSourceSetting = (RelativeLayout) findViewById(R.id.rlVideoSourceSetting);
        tvTVNum = (TextView) findViewById(R.id.tvTVNum);
        tvSerachType = (TextView) findViewById(R.id.tvSerachType);
        tvVideoSourceText = (TextView) findViewById(R.id.tvVideoSourceText);
        tbToolbar=(Toolbar)findViewById(R.id.tbToolbar);

        mAdapter = new MenuTvContentAdapter(this, items);
        mListView.setAdapter(mAdapter);
        igBackImg = (ImageView) findViewById(R.id.igBackImg);

        //加载本地缓存的----影视来源个数和选中的个数
        tvVideoSourceText.setText(VideoSourceSqlData.getDbDataManager().getSelectVideoSourceNumber());
    }
}

